<template>
    <view class="container">
        <!-- 自定义导航栏 -->
        <custom-navbar :showTitle="true" title="积分记录" :isCoverNav="false" backgroundColor="#ffffff" textColor="#333333" :showBack="true"></custom-navbar>
        
        <!-- 积分总览 -->
        <view class="points-overview">
            <view class="total-points">
                <text class="points-label">当前积分</text>
                <text class="points-value">{{ totalPoints }}</text>
            </view>
        </view>

        <!-- 积分记录列表 -->
        <scroll-view 
            class="records-container" 
            scroll-y="true" 
            enable-back-to-top="true" 
            :style="{ height: scrollViewHeight }"
            @scrolltolower="onLoadMore"
            :refresher-enabled="true"
            :refresher-triggered="refreshing"
            @refresherrefresh="onRefresh"
        >
            <view v-if="loading && pointsRecords.length === 0" class="loading-container">
                <u-loading-icon mode="spinner" size="40"></u-loading-icon>
                <text class="loading-text">加载中...</text>
            </view>
            
            <view v-else-if="pointsRecords.length === 0 && !loading" class="empty-container">
                <u-empty mode="data" text="暂无积分记录">
                    <template #button>
                        <u-button type="primary" size="small" @click="getPointsRecords">重新加载</u-button>
                    </template>
                </u-empty>
            </view>
            
            <view v-else class="records-list">
                <view v-for="(record, index) in pointsRecords" :key="record.id || index" class="record-item">
                    <view class="record-content">
                        <view class="record-left">
                            <view class="record-title">{{ record.title }}</view>
                            <view class="record-time">{{ formatTime(record.createTime) }}</view>
                            <view v-if="record.description" class="record-desc">{{ record.description }}</view>
                        </view>
                        <view class="record-right">
                            <text class="points-change" :class="record.type === 'add' ? 'points-add' : 'points-minus'">
                                {{ record.type === 'add' ? '+' : '-' }}{{ record.points }}
                            </text>
                        </view>
                    </view>
                </view>
                
                <!-- 加载更多提示 -->
                <view v-if="hasMore" class="load-more">
                    <view v-if="loadingMore" class="loading-more">
                        <u-loading-icon mode="spinner" size="24"></u-loading-icon>
                        <text class="loading-more-text">加载中...</text>
                    </view>
                    <view v-else class="load-more-text">上拉加载更多</view>
                </view>
                
                <view v-else-if="pointsRecords.length > 0" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import customNavbar from '../../components/custom-navbar/index.vue'
import { userPointFun } from '@/api/port'
// 类型定义
interface PointsRecord {
    id: number
    title: string
    points: number
    type: 'add' | 'minus'
    createTime: string
    description?: string
}

interface LoadOptions {
    [key: string]: any
}

// 响应式数据
const totalPoints = ref<number>(1250)
const pointsRecords = ref<PointsRecord[]>([])
const loading = ref<boolean>(false)
const refreshing = ref<boolean>(false)
const loadingMore = ref<boolean>(false)
const hasMore = ref<boolean>(true)
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const scrollViewHeight = ref<string>('auto')

// 模拟积分记录数据
const mockPointsRecords: PointsRecord[] = [
    {
        id: 1,
        title: '完成订单获得积分',
        points: 50,
        type: 'add',
        createTime: '2024-01-15 14:30:25',
        description: '订单号：202401150001'
    },
    {
        id: 2,
        title: '订房抵扣积分扣除',
        points: 100,
        type: 'minus',
        createTime: '2024-01-14 10:15:30',
        description: '兑换商品：精美礼品'
    },
    {
        id: 3,
        title: '完成订单获得积分',
        points: 10,
        type: 'add',
        createTime: '2024-01-14 09:00:00',
        description: '每日签到奖励'
    },
    {
        id: 4,
        title: '发布故事获得积分',
        points: 20,
        type: 'add',
        createTime: '2024-01-13 16:45:12',
        description: '订单号：202401130002'
    },
    {
        id: 5,
        title: '订房抵扣积分扣除',
        points: 30,
        type: 'minus',
        createTime: '2024-01-12 00:00:00',
        description: '积分有效期已过'
    },
    {
        id: 6,
        title: '新用户注册奖励',
        points: 100,
        type: 'add',
        createTime: '2024-01-10 12:00:00',
        description: '欢迎加入会员'
    },
    {
        id: 7,
        title: '完成订单获得积分',
        points: 50,
        type: 'add',
        createTime: '2024-01-15 14:30:25',
        description: '订单号：202401150001'
    },
    {
        id: 8,
        title: '订房抵扣积分扣除',
        points: 100,
        type: 'minus',
        createTime: '2024-01-14 10:15:30',
        description: '兑换商品：精美礼品'
    },
    {
        id: 9,
        title: '完成订单获得积分',
        points: 10,
        type: 'add',
        createTime: '2024-01-14 09:00:00',
        description: '每日签到奖励'
    },
    {
        id: 10,
        title: '发布故事获得积分',
        points: 20,
        type: 'add',
        createTime: '2024-01-13 16:45:12',
        description: '订单号：202401130002'
    },
    {
        id: 11,
        title: '订房抵扣积分扣除',
        points: 30,
        type: 'minus',
        createTime: '2024-01-12 00:00:00',
        description: '积分有效期已过'
    },
    {
        id: 12,
        title: '新用户注册奖励',
        points: 100,
        type: 'add',
        createTime: '2024-01-10 12:00:00',
        description: '欢迎加入会员'
    }
]

// 格式化时间
const formatTime = (timeStr: string): string => {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
            const minutes = Math.floor(diff / (1000 * 60))
            return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
        }
        return `${hours}小时前`
    } else if (days === 1) {
        return '昨天'
    } else if (days < 7) {
        return `${days}天前`
    } else {
        return timeStr.split(' ')[0]
    }
}

// 获取积分记录
const getPointsRecords = async (isRefresh: boolean = false, isLoadMore: boolean = false): Promise<void> => {
    if (isRefresh) {
        refreshing.value = true
        currentPage.value = 1
        hasMore.value = true
    } else if (isLoadMore) {
        if (!hasMore.value || loadingMore.value) return
        loadingMore.value = true
        currentPage.value += 1
    } else {
        loading.value = true
        currentPage.value = 1
        hasMore.value = true
    }
    
    try {
        const params = {
            page: currentPage.value,
            limit: pageSize.value
        }
        
        const res = await userPointFun(params)
        if (res.code === 200 && res.data) {
            // 处理API返回的数据
            if (res.data.total_points !== undefined) {
                totalPoints.value = res.data.total_points
            }
            
            let newRecords: PointsRecord[] = []
            if (res.data.records && Array.isArray(res.data.records)) {
                newRecords = res.data.records.map((item: any) => ({
                    id: item.id,
                    title: item.title || item.description || '积分变动',
                    points: Math.abs(item.points || item.amount || 0),
                    type: (item.points || item.amount || 0) > 0 ? 'add' : 'minus',
                    createTime: item.create_time || item.createTime || new Date().toISOString(),
                    description: item.description || item.remark || ''
                }))
                
                // 检查是否还有更多数据
                hasMore.value = newRecords.length >= pageSize.value
            } else {
                // 如果API没有返回记录数据，使用模拟数据
                const startIndex = (currentPage.value - 1) * pageSize.value
                const endIndex = startIndex + pageSize.value
                newRecords = mockPointsRecords.slice(startIndex, endIndex)
                hasMore.value = endIndex < mockPointsRecords.length
            }
            
            if (isRefresh || !isLoadMore) {
                pointsRecords.value = newRecords
            } else {
                pointsRecords.value = [...pointsRecords.value, ...newRecords]
            }
        } else {
            // API调用失败，使用模拟数据
            const startIndex = (currentPage.value - 1) * pageSize.value
            const endIndex = startIndex + pageSize.value
            const newRecords = mockPointsRecords.slice(startIndex, endIndex)
            hasMore.value = endIndex < mockPointsRecords.length
            
            if (isRefresh || !isLoadMore) {
                pointsRecords.value = newRecords
            } else {
                pointsRecords.value = [...pointsRecords.value, ...newRecords]
            }
        }
    } catch (error) {
        console.error('获取积分记录失败:', error)
        // 网络错误时使用模拟数据
        const startIndex = (currentPage.value - 1) * pageSize.value
        const endIndex = startIndex + pageSize.value
        const newRecords = mockPointsRecords.slice(startIndex, endIndex)
        hasMore.value = endIndex < mockPointsRecords.length
        
        if (isRefresh || !isLoadMore) {
            pointsRecords.value = newRecords
        } else {
            pointsRecords.value = [...pointsRecords.value, ...newRecords]
        }
        
        if (!isRefresh && !isLoadMore) {
            uni.showToast({
                title: '网络异常，显示本地数据',
                icon: 'none',
                duration: 2000
            })
        }
    } finally {
        loading.value = false
        refreshing.value = false
        loadingMore.value = false
    }
}

// 下拉刷新
const onRefresh = (): void => {
    getPointsRecords(true, false)
}

// 上拉加载更多
const onLoadMore = (): void => {
    if (hasMore.value && !loadingMore.value) {
        getPointsRecords(false, true)
    }
}

// 页面下拉刷新（兼容旧版本）
const onPagePullDownRefresh = (): void => {
    getPointsRecords(true, false).then(() => {
        uni.stopPullDownRefresh()
    })
}

// 页面加载
const onPageLoad = (options: LoadOptions): void => {
    getPointsRecords()
}

// 计算scroll-view高度
const calculateScrollViewHeight = (): void => {
    try {
        // 从localStorage获取导航栏高度
        const navHeight = uni.getStorageSync('navHeight') || 88
        
        // 获取points-overview元素高度
        const query = uni.createSelectorQuery()
        query.select('.points-overview').boundingClientRect((data: any) => {
            if (data) {
                const pointsOverviewHeight = data.height
                // 计算scroll-view高度：100vh - 导航栏高度 - points-overview高度 - 底部间距
                scrollViewHeight.value = `calc(100vh - ${navHeight}px - ${pointsOverviewHeight}px - 20rpx)`
            }
        }).exec()
    } catch (error) {
        console.error('计算高度失败:', error)
        // 降级方案
        scrollViewHeight.value = 'calc(100vh - 88px - 140rpx - 20rpx)'
    }
}

// 页面挂载
onMounted(() => {
    onPageLoad({})
    // 延迟计算高度，确保DOM渲染完成
    setTimeout(() => {
        calculateScrollViewHeight()
    }, 100)
})

// 暴露变量和方法
defineExpose({
    totalPoints,
    pointsRecords,
    loading,
    refreshing,
    loadingMore,
    hasMore,
    currentPage,
    pageSize,
    scrollViewHeight,
    getPointsRecords,
    onPageLoad,
    onPagePullDownRefresh,
    onRefresh,
    onLoadMore,
    formatTime,
    calculateScrollViewHeight
})
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    background-color: #f5f5f5;
}

/* 积分总览区域 */
.points-overview {
    background-color: #ffffff;
    padding: 40rpx 30rpx;
    margin-bottom: 20rpx;
}

.total-points {
    text-align: center;
}

.points-label {
    display: block;
    font-size: 28rpx;
    color: #666666;
    margin-bottom: 10rpx;
}

.points-value {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #ff6b35;
}

/* 记录容器 */
.records-container {
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    overflow: hidden;
}

/* 加载状态 */
.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
}

.loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999999;
}

/* 空状态 */
.empty-container {
    padding: 100rpx 0;
}

/* 记录列表 */
.records-list {
    padding: 0 30rpx;
}

.record-item {
    border-bottom: 1rpx solid #f0f0f0;
}

.record-item:last-child {
    border-bottom: none;
}

.record-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 0;
}

.record-left {
    flex: 1;
}

.record-title {
    font-size: 32rpx;
    color: #333333;
    margin-bottom: 10rpx;
    font-weight: 500;
}

.record-time {
    font-size: 24rpx;
    color: #999999;
}

.record-desc {
    font-size: 24rpx;
    color: #666666;
    margin-top: 8rpx;
    line-height: 1.4;
}

.record-right {
    margin-left: 20rpx;
}

.points-change {
    font-size: 32rpx;
    font-weight: bold;
}

.points-add {
    color: #52c41a;
}

.points-minus {
    color: #ff4d4f;
}

/* 加载更多样式 */
.load-more {
    padding: 30rpx 0;
    text-align: center;
}

.loading-more {
    display: flex;
    align-items: center;
    justify-content: center;
}

.loading-more-text {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #999999;
}

.load-more-text {
    font-size: 28rpx;
    color: #999999;
}

.no-more {
    padding: 30rpx 0;
    text-align: center;
}

.no-more-text {
    font-size: 28rpx;
    color: #cccccc;
}
</style>
